<route lang="json5" type="page">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '入驻',
  },
}
</route>

<template>
  <view>
    <!-- 定位栏 -->
    <view class="location-bar">
      <view class="location-left" @tap="goToCitySelect">
        <wd-icon name="location" size="32rpx" color="#333"></wd-icon>
        <text class="location-text">{{ address }}</text>
        <wd-icon name="arrow-down" size="26rpx" color="#666"></wd-icon>
      </view>
      <view class="location-right" @tap="showModeSelect">
        <wd-icon name="list" size="32rpx" color="#333"></wd-icon>
      </view>
    </view>

    <!-- 搜索栏 -->
    <view class="search-bar">
      <wd-search disabled hide-cancel light />
    </view>

    <view class="pt-20rpx">
      <SettledList ref="settledRef" />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { ref, reactive, onUnmounted, shallowRef } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { QQMapWX } from '@/lib/qqmap-wx-jssdk.js'
import { QqMapKey } from '@/config/key'
import SettledList from './components/settled-list.vue'

const settledRef = shallowRef()
const chooseLocation = requirePlugin('chooseLocation')
const choosePoint = reactive({
  latitude: 0,
  longitude: 0,
})
const address = ref('正在获取当前地理位置...')
const searchValue = ref('')
const qqmapsdk = new QQMapWX({
  key: QqMapKey, // 必填
})

// 获取当前位置
const getCurrentLocation = () => {
  // 检查位置权限
  uni.getSetting({
    success: (res) => {
      if (!res.authSetting['scope.userLocation']) {
        uni.authorize({
          scope: 'scope.userLocation',
          success: () => {
            requestLocation()
          },
          fail: () => {
            uni.showModal({
              title: '提示',
              content: '需要您授权位置信息才能使用此功能',
              success: (res) => {
                if (res.confirm) {
                  uni.openSetting()
                }
              },
            })
          },
        })
      } else {
        requestLocation()
      }
    },
  })
}

const getLocation = (latitude, longitude) => {
  qqmapsdk.reverseGeocoder({
    location: {
      latitude,
      longitude,
    },
    success: function (res: any) {
      // 成功后的回调
      console.log('逆地址解析成功:', res)
      if (res.status === 0) {
        if (res.result.title) {
          address.value = res.result.title
        } else {
          address.value = res.result.formatted_addresses.recommend
        }
      } else {
        uni.showToast({
          title: '获取地址失败',
          icon: 'none',
        })
      }
    },
    fail: function (error: any) {
      console.error(error)
    },
    complete: function (res: any) {
      console.log(res)
    },
  })
}

const requestLocation = () => {
  uni.getLocation({
    type: 'gcj02',
    altitude: true,
    success: (res) => {
      console.log('获取位置成功:', res)
      const { latitude, longitude } = res
      choosePoint.latitude = latitude
      choosePoint.longitude = longitude
      getLocation(latitude, longitude)
    },
    fail: (error) => {
      console.error('获取位置失败:', error)
      uni.showToast({
        title: '获取位置失败',
        icon: 'none',
      })
    },
  })
}

// 添加选择模式相关代码
const showModeSelect = (): void => {
  uni.showActionSheet({
    itemList: ['最多空位停车场', '最近停车场'],
    success: (res) => {
      const mode = res.tapIndex === 0 ? 'mostSpaces' : 'nearest'
      // 这里可以添加根据模式筛选停车场的逻辑
      uni.showToast({
        title: mode === 'mostSpaces' ? '已切换至最多空位模式' : '已切换至最近停车场模式',
        icon: 'none',
      })
    },
  })
}

// 跳转到城市选择页面
const goToCitySelect = (): void => {
  const key = QqMapKey // 使用在腾讯位置服务申请的key
  const referer = 'car_shop' // 调用插件的app的名称
  const location = JSON.stringify(choosePoint)
  // 其他需要的参数，可以查看文档
  uni.navigateTo({
    url: `plugin://chooseLocation/index?key=${key}&referer=${referer}&location=${location}`,
  })
}

watch(
  () => choosePoint,
  () => {
    if (choosePoint.latitude && choosePoint.longitude) {
      refreshPageData()
    }
  },
  {
    immediate: true,
    deep: true,
  },
)

const refreshPageData = () => {
  settledRef.value.reloadPage(choosePoint)
}

// 监听位置更新事件
onShow(() => {
  const locationPoint = chooseLocation.getLocation()
  console.log('选点结果:', location)
  if (locationPoint) {
    console.log('用户选择了地点:', locationPoint)
    choosePoint.latitude = locationPoint.latitude
    choosePoint.longitude = locationPoint.longitude
    // location 不为 null 时再访问属性
    address.value = locationPoint.name
    // 其它逻辑...
  } else {
    // 用户未选择地点或取消
    console.log('未选择地点')
  }
})

onLoad((options) => {
  getCurrentLocation()
})
</script>

<style lang="scss" scoped>
.location-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #ffffff;

  .location-left {
    display: flex;
    align-items: center;

    .location-text {
      margin: 0 10rpx;
      font-size: 28rpx;
      color: #333;
    }
  }

  .location-right {
    display: flex;
    align-items: center;
  }
}

.search-bar {
  padding: 20rpx 30rpx;
  background-color: #ffffff;
}
</style>
